<template>
  <div class="auth-page">
    <div class="container page">
      <div class="row">
        <div class="col-md-6 offset-md-3 col-xs-12">
          <!-- 登录与注册显示不同的标题 -->
          <h1 class="text-xs-center">{{ isLogin ? "Sign up" : "Sign in" }}</h1>
          <p class="text-xs-center">
            <!-- 有账号，去登录 -->
            <nuxt-link to="/login" v-if="!isLogin">Have an account?</nuxt-link>
            <!-- 无账号，去注册 -->
            <nuxt-link to="/register" v-else>Need an account?</nuxt-link>
          </p>
          <!-- 登录或注册报错信息展示 -->
          <ul class="error-messages">
            <template v-for="(value, msg) in errors">
              <li v-for="(item, index) in value" :key="index">{{msg}} {{item}}</li>
            </template>
          </ul>
          <!-- 登录|注册表单信息 -->
          <form @submit.prevent="onSubmit">
            <fieldset class="form-group" v-if="!isLogin">
              <input  class="form-control form-control-lg" type="text" v-model.trim="user.username" placeholder="Your Name" required  />
            </fieldset>
            <fieldset class="form-group">
              <input class="form-control form-control-lg" type="text"  v-model.trim="user.email" placeholder="Email" required />
            </fieldset>
            <fieldset class="form-group">
              <input class="form-control form-control-lg" type="password"  v-model.trim="user.password" placeholder="Password" required />
            </fieldset>
            <button class="btn btn-lg btn-primary pull-xs-right"> {{ isLogin ? "Sign up" : "Sign in" }} </button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { login, register } from '@/api/login'
import { mapMutations } from 'vuex'
// 仅在客户端加载 js-cookie 包
const Cookie = process.client ? require('js-cookie') : undefined
export default {
  middleware: 'notAuthenticated',
  data() {
    return {
      user: {
        username: '', //用户姓名
        email: '', // 邮箱
        password: '' //密码
      },
      errors:{} // 登录|注册错误信息
    };
  },
  computed: {
    // 根据页面名称判断当前是登录还是注册
    isLogin() {
      return this.$route.name === "login";
    }
  },
  created(){
    // 进入页面清空之前的数据
    this.user =  this.$options.data().user
    this.errors = this.$options.data().errors
  },
  methods:{
    // 引入mutations中的setUser方法
    ...mapMutations({setUser: 'user/setUser'}),
    // 登录|注册方法
   async onSubmit(){
      try {
        // 请求登录|注册接口
        const { user } = this.isLogin ?  await login({user: {email: this.user.email, password: this.user.password}}) :  await register({user: this.user})
        // 在vuex中保存用户登录状态
        this.setUser(user)
        // 在cookie中保存信息 把数据持久化
        Cookie.set('user', user)
        // 跳转至首页
        this.$router.push('/')
      } catch (err) {
        // 报错登录|注册错误信息
        this.errors = err
      }
    }
  }
};
</script>
